package org.kugua.library.impl;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.kugua.common.Constants;
import org.kugua.library.QuestionAnswer;
import org.kugua.library.QuestionAnswerLibrary;
import org.kugua.utils.RandomUtils;
import org.springframework.core.io.ClassPathResource;

import com.alibaba.fastjson2.JSON;

/**
 * MemoryQALibrary
 *
 * @author 苦瓜
 * @create 2024-08-27
 * @since 1.0.0
 */
public class MemoryQALibrary implements QuestionAnswerLibrary {

    public static final String JSON_LIBRARY_NAME = "library.json";
    private final static List<QuestionAnswer> library = new ArrayList<>();

    static {
        try {
            ClassPathResource classPathResource = new ClassPathResource(Constants.Path.LIBRARY_PATH + File.separator + JSON_LIBRARY_NAME);
            String contentAsString = classPathResource.getContentAsString(StandardCharsets.UTF_8);
            List<QuestionAnswer> questionAnswers = JSON.parseArray(contentAsString, QuestionAnswer.class);
            library.addAll(questionAnswers);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 随机获取1个QA
     *
     * @return QuestionAnswer
     */
    @Override
    public QuestionAnswer randomOne() {
        Integer random = RandomUtils.random(library.size());
        return library.get(random);
    }

    /**
     * 随机获取1个指定answer的QA
     *
     * @param answer 答案
     * @return QuestionAnswer
     */
    @Override
    public QuestionAnswer randomOne(String answer) {
        List<QuestionAnswer> collect = library.parallelStream()
                .filter(r -> Optional.ofNullable(r.getAnswer()).orElseGet(ArrayList::new)
                        .contains(answer))
                .toList();
        // 不存在的时候，随机返回1个
        if (collect.isEmpty()) {
            return randomOne();
        }
        Integer random = RandomUtils.random(collect.size());
        return collect.get(random);
    }
}
